﻿namespace VividKit.ServiceModel
{
	using System;
	using System.Diagnostics;
	using System.Threading.Tasks;

	public class TraceEventDispatcher : IEventDispatcher
	{
		private readonly IEventDispatcher eventDispatcher;

		public TraceEventDispatcher(IEventDispatcher eventDispatcher)
		{
			this.eventDispatcher = eventDispatcher;
		}

		public async Task PublishAsync<TEvent>(TEvent e) where TEvent : class, IEvent
		{
			var stopwatch = new Stopwatch();
			try
			{
				Debug.WriteLine("Publishing {0}", e.GetType().Name);

				stopwatch.Start();
				await this.eventDispatcher.PublishAsync(e);
			}
			catch (Exception x)
			{
				Debug.WriteLine(x.ToString());
				throw;
			}
			finally
			{
				stopwatch.Stop();
				Debug.WriteLine("Published {0} ({1} ms)",
					e.GetType().Name, stopwatch.ElapsedMilliseconds);
			}
		}
	}
}